#include "users.h"
#include "mysql.h"

#define USER_PASSWD_LENGTH 20



int user_login(pFactory_t pfac,int newFd,puserNode *outuser)
{

    //用户节点
    puserNode newUser = (puserNode)calloc(sizeof(userNode_t), 1);

    (newUser)->fd = newFd;
    (newUser)->next = NULL;
    //通信 接收用户信息
    char userName[USER_NAME_LENGTH] = {0};
    char passWd[USER_PASSWD_LENGTH+1] = {0};
    int len = 0;
    int flag = 0;
    while(!flag)
    {
        recvCyc(newFd, &len, sizeof(int));
        if(!len)
        {
            free(newUser);
            return -1;
        }
        recvCyc(newFd, userName , len);
        recvCyc(newFd, &len, sizeof(int));
        recvCyc(newFd, passWd, len);

        printf("get userName: %s\nget userPasswd: %s\n", userName, passWd);

        //查询数据库

        char stdPasswd[USER_PASSWD_LENGTH + 1] = {0};
        getPasswdByUserName(userName, stdPasswd);
        
        if (strcmp(passWd, stdPasswd) == 0) //密码验证通过 发送1
        {
            flag = 1;
            send(newFd, &flag, sizeof(int), 0);
            strcpy((newUser)->userName,userName);
            sprintf((newUser)->homePath, "./userHome/%s", userName);
            *(outuser) = newUser;
            return 0;
        }
        else//密码验证失败 发送0 
        {
            send(newFd, &flag, sizeof(int), 0);
            free(newUser);
            return -1;
        }
    }
}